import { z } from "zod";
import { prisma } from '../../../service/mysql.js';
function getRandomSixDigitNumber() {
    // 使用 Date.now() 生成新的种子
    return Math.floor((Math.random() * Date.now()) % 900000) + 100000;
}

export default {
    api: "loginFunds",
    name: "获取登录后台的凭证",
    description: "判断客户是否需要登录后台，给予账务后台的登录凭证，比如：我要登录后台。",
    requestSchema: z.any(),
    func: async (arg, context) => {
        let accountUser = await prisma.t_accounts.findFirst({
            where: {
                account_no: context.user.id
            }
        });
        let certificate = accountUser?.account_certificate;
        if (!accountUser) {
            // 检查凭证是否重复
            let retry = 0;
            while (true) {
                certificate = `${getRandomSixDigitNumber()}`;
                const cnt = await prisma.t_accounts.count({
                    where: {
                        account_certificate: certificate
                    }
                });
                retry++;
                if (cnt < 1) {
                    break;
                }
                if (retry > 10) {
                    throw new Error('无法初始化登录凭证，请联系系统管理员...');
                }
            }
            // 创建凭证
            await prisma.t_accounts.create({
                data: {
                    gmt_create: new Date(),
                    account_no: context.user.id,
                    account_certificate: certificate
                }
            });
        }
        return `${context.user.name}您好，您的登录凭证为【${certificate}】，请勿泄漏凭证码，可使用该凭证登录小钱钱后台 https://funds-gpt.chenjianhui.site`;
    }
}